package cn.daniellee.plugin;

import cn.daniellee.plugin.component.RewardSender;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OnlineRewards extends JavaPlugin {

	public static final String PREFIX = "&7[&6OnlineRewards&7] &3: &r".replace("&", "§");
	
	public static FileConfiguration config;

	private static RewardSender rewardSender = new RewardSender();

	private static long interval;

	private static FileConfiguration checkin = new YamlConfiguration();

	private static File checkin_file;

	@Override
	public void onEnable() {
		loadConfig();

		checkin_file = new File(getDataFolder(), "checkin.yml");
		try {
			if (!checkin_file.exists()) checkin_file.createNewFile();
			checkin.load(checkin_file);
		} catch (Exception e) {
			getLogger().info(e.toString());
			getLogger().info("[OnlineRewards]" + config.get("checkin-file-error"));
		}

		getLogger().info(" ");
		getLogger().info(">>>>>>>>>>>>>>>>>>>>>>>> OnlineRewards Loaded <<<<<<<<<<<<<<<<<<<<<<<<");
		getLogger().info(">>>>> If you encounter any bugs, please contact author's QQ: 768318841 <<<<<");
		getLogger().info(" ");

		Bukkit.getPluginCommand("qd").setExecutor(this);
		Bukkit.getPluginCommand("or").setExecutor(this);

		interval = config.getInt("reward-interval", 30);
		rewardSender.runTaskTimer(this, 0L, 20 * interval);
	}

	private void loadConfig() {
		getLogger().info("[OnlineRewards] Loading config...");
		config = getConfig();
		if(!getDataFolder().exists()) getDataFolder().mkdirs();
		saveDefaultConfig();
	}

	@Override
	public void onDisable() {
		if (!rewardSender.isCancelled()) rewardSender.cancel();

		getLogger().info(" ");
		getLogger().info(">>>>>>>>>>>>>>>>>>>>>>>> OnlineRewards Unloaded <<<<<<<<<<<<<<<<<<<<<<<<");
		getLogger().info(" ");
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if ("qd".equalsIgnoreCase(command.getName())) {
			if (!(sender instanceof Player)) {
				sender.sendMessage(PREFIX + config.get("console-cant-run"));
				return true;
			}
			Player player = (Player) sender;
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String today = format.format(new Date());
			if (!today.equals(checkin.getString(player.getName() + ".last"))) {
				checkin.set(player.getName() + ".last", today);
				checkin.set(player.getName() + ".total", checkin.getInt(player.getName() + ".total") + 1);
				player.playSound(player.getLocation(), Sound.BLOCK_SAND_BREAK, 1, 1);
				String cmd = (String) config.get("checkin-command");
				if (cmd.contains("%p%")) cmd = cmd.replace("%p%", player.getName());
				if (cmd.contains("%player%")) cmd = cmd.replace("%player%", player.getName());
				this.getServer().dispatchCommand(this.getServer().getConsoleSender(), cmd);
				player.sendMessage(PREFIX + config.get("checkin-success"));
				try {
					checkin.save(checkin_file);
				} catch (IOException e) {
					getLogger().info(e.toString());
					getLogger().info("[OnlineRewards]" + config.get("checkin-file-error"));
				}
			} else player.sendMessage(PREFIX + config.get("already-checkin"));
		} else if ("or".equalsIgnoreCase(command.getName())) {
			if (!sender.isOp()) {
				sender.sendMessage(PREFIX + config.get("only-op"));
				return true;
			}
			if (args.length == 0) {
				sendHelp(sender);
				return true;
			}
			if ("reload".equalsIgnoreCase(args[0])) {
				reloadConfig();
				config = getConfig();
				int newInterval = config.getInt("reward-interval", 30);
				if (interval != newInterval) {
				    interval = newInterval;
					rewardSender.cancel();
					rewardSender = new RewardSender();
					rewardSender.runTaskTimer(this, 0L, 20 * interval);
				}
				try {
					if (!checkin_file.exists()) checkin_file.createNewFile();
					checkin.load(checkin_file);
				} catch (Exception e) {
					getLogger().info(e.toString());
					getLogger().info("[OnlineRewards]" + config.get("checkin-file-error"));
				}
				sender.sendMessage(PREFIX + config.get("reload-success"));
			} else if ("interval".equalsIgnoreCase(args[0]) && args.length > 1) {
				int newInterval;
				try {
					newInterval = Integer.valueOf(args[1]);
				} catch (NumberFormatException e) {
					sender.sendMessage(PREFIX + config.get("interval-only-int"));
					return true;
				}
				if (interval != newInterval) {
					interval = newInterval;
					rewardSender.cancel();
					rewardSender = new RewardSender();
					rewardSender.runTaskTimer(this, 0L, 20 * interval);
					config.set("reward-interval", interval);
					saveConfig();
				}
				sender.sendMessage(PREFIX + config.get("interval-modified"));
			} else if ("reward".equalsIgnoreCase(args[0]) && args.length > 1) {
				String cmd = StringUtils.join(args, " ");
				config.set("reward-command", cmd.substring(cmd.indexOf(" ") + 1));
				saveConfig();
				sender.sendMessage(PREFIX + config.get("reward-modified"));
			} else if ("checkin".equalsIgnoreCase(args[0]) && args.length > 1) {
				String cmd = StringUtils.join(args, " ");
				config.set("checkin-command", cmd.substring(cmd.indexOf(" ") + 1));
				saveConfig();
				sender.sendMessage(PREFIX + config.get("checkin-modified"));
			} else sendHelp(sender);
		}
		return true;
	}

	private void sendHelp(CommandSender sender) {
		sender.sendMessage("§m§a---§m§6--------§3 : " + PREFIX + "§m§a--------§m§6---");

		TextComponent reloadHelp = new TextComponent("/or reload  " + config.get("reload-help"));
		reloadHelp.setColor(ChatColor.GRAY);
		reloadHelp.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/or reload"));
		reloadHelp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder((String) config.get("reload-help")).color(ChatColor.BLUE).create()));
		sender.spigot().sendMessage(reloadHelp);

		TextComponent intervalHelp = new TextComponent("/or interval <number>  " + config.get("interval-help"));
		intervalHelp.setColor(ChatColor.GRAY);
		intervalHelp.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/or interval "));
		intervalHelp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder((String) config.get("interval-help")).color(ChatColor.BLUE).create()));
		sender.spigot().sendMessage(intervalHelp);

		TextComponent rewardHelp = new TextComponent("/or reward <command>  " + config.get("reward-help"));
		rewardHelp.setColor(ChatColor.GRAY);
		rewardHelp.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/or reward "));
		rewardHelp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder((String) config.get("reward-help")).color(ChatColor.BLUE).create()));
		sender.spigot().sendMessage(rewardHelp);

		TextComponent checkinHelp = new TextComponent("/or checkin <command>  " + config.get("checkin-help"));
		checkinHelp.setColor(ChatColor.GRAY);
		checkinHelp.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/or checkin "));
		checkinHelp.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder((String) config.get("checkin-help")).color(ChatColor.BLUE).create()));
		sender.spigot().sendMessage(checkinHelp);

	}

}
